<?php

namespace App\Http\Controllers\Backstage\System;

use App\Http\Controllers\BaseController;
use App\Http\Requests\Backstage\System\Region\CreateRequest;
use App\Http\Requests\Backstage\System\Region\UpdateRequest;
use App\Models\System\Region;
use App\Transformers\System\RegionTransformer;
use Illuminate\Http\Request;
use Overtrue\Pinyin\Pinyin;

class RegionController extends BaseController
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        $page_size = get_request_page();
        if ($page_size) {
            $models = Region::whereLevel(Region::LEVEL)->paginate($page_size);
            return $this->response->paginator($models, new RegionTransformer());
        }
        $models = Region::whereLevel(\request()->get('level', Region::LEVEL))->get();
        return $this->response->collection($models, new RegionTransformer());
    }

    /**
     * @param CreateRequest $request
     * @throws \Throwable
     */
    public function store(CreateRequest $request)
    {
        \DB::transaction(function () use ($request) {
            $attributes = $request->validated();
            $attributes['level'] = Region::LEVEL;
            $attributes['initials'] = $this->pinYin(array_get($attributes, 'name'));
            $model = Region::create($attributes);
            return $model;
        });
    }

    public function show($id)
    {
        $region = Region::whereId($id)->first();
        return $this->response->item($region, new RegionTransformer());
    }

    /**
     * @param UpdateRequest $request
     * @param $id
     * @throws \Throwable
     */
    public function update(UpdateRequest $request, $id)
    {
        \DB::transaction(function () use ($request, $id) {
            $attributes = $request->validated();
            $attributes['level'] = Region::LEVEL;
            $model = Region::whereId($id)->first();
            $attributes['initials'] = $this->pinYin(array_get($attributes, 'name'));
            $model->update($attributes);
            return $model;
        });
    }

    private function pinYin(string $name)
    {
        $pinyin = new Pinyin();
        return $pinyin->permalink($name, '');
    }

}
